package vip.ola.pay.channel.chargezfb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.PayOrder;
import vip.ola.core.entity.PayPassageAccount;
import vip.ola.pay.channel.BasePayment;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static vip.ola.core.common.constant.PayEnum.ERR_0010;
import static vip.ola.core.common.constant.PayEnum.ERR_0121;

@Service
public class ChargezfbPaymentService extends BasePayment {

    private static final MyLog _log = MyLog.getLog(ChargezfbPaymentService.class);

    @Override
    public String getChannelName() {
        return null;
    }

    @Override
    public JSONObject pay(PayOrder payOrder) {
        try {
            _log.info("话费支付使用子账号ID：" + payOrder.getChannelMchId());
            PayPassageAccount payPassageAccount = rpcCommonService.rpcPayPassageAccountService.findById(payOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
            String mchId = payPassageAccount.getPassageMchId();
            BigDecimal amount = new BigDecimal(payOrder.getAmount()).divide(new BigDecimal(100)).setScale(2);
            String orderId = payOrder.getPayOrderId();
            String prePayUrl = accountParams.getString("payUrl");
            String payUrl = "";
            Map<String,String> map = new HashMap<>();
            map.put("merchantId",mchId);
            map.put("payType","alipay");
            map.put("notifyUrl",accountParams.getString("notify_url"));
            map.put("money",amount.toString());
            map.put("orderNo",orderId);
            map.put("sign",getSign(map,payPassageAccount.getPrivateKey()));
            _log.info("商户 "+payOrder.getMchId()+" 启用匹配页面" );
            //这里是外部拉单服务器，
            String[] domains = accountParams.getString("orderUrl").split(",");
            int index = (int) (Math.random() * domains.length);
            String domian = domains[index];
            String getOrderUrl = "http://"+domian+"?payUrl=" + prePayUrl + "&orderNo=" + orderId + "&money=" + amount +"&payType=" + map
                        .get("payType") +
                        "&merchantId=" +mchId +
                        "&sign=" + map
                        .get("sign") +
                        "&notifyUrl=" + map.get("notifyUrl");
            _log.info("最终拉单连接:" + getOrderUrl);
            int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
            _log.info("更新订单状态为支付中: result={}", result);
            return PayUtil.makeRetPayUrl(getOrderUrl, null);
        }catch (Exception e){
            _log.error(e, "调用话费渠道异常。");
            return PayUtil.makeRetFail(ERR_0010);
        }
    }

    public static String getSign(Map<String,String> param, String signKey){
        SortedMap<String,String> map = new TreeMap<>(param);
        String str = "";
        map.remove("sign");
        for (Map.Entry<String,String> entry : map.entrySet()){
            if (entry.getValue() == null || "".equals(entry.getValue()) || "sign".equals(entry.getKey()))continue;
            str += entry.getValue();
        }
        return PayDigestUtil.md5(str+signKey,"UTF-8");
    }

    public static String call(String url, Map<String,String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            _log.info("请求参数："+uri.toString());
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


    @Override
    public JSONObject query(PayOrder payOrder) {
        return null;
    }
}
